<template>
    <div>
        <!-- 面包屑导航区域 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
            <el-row>
                <el-col>
                    <el-button type="primary" @click="addRolesDialogVisiable = true">添加角色</el-button>
                </el-col>
            </el-row>
            <el-table :data="roleList" border stripe>
                <!-- 展开列 -->
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <el-row :class="['bdbottom','vcenter',i1 === 0 ? 'bdtop' : '']" v-for="(item1,i1) in scope.row.children" :key="item1.id">
                            <el-col :span="5">
                                <el-tag>
                                    {{item1.authName}}
                                </el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <el-col :span="19">
                                <!-- for循环渲染所有的二级权限 -->
                                <el-row :class="['vcenter',i2 === 0 ? '' : 'bdtop']" v-for="(item2,i2) in item1.children" :key="item2.id">
                                    <el-col :span="6">
                                        <el-tag type="success">
                                            {{item2.authName}}
                                        </el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <!-- 三级权限 -->
                                    <el-col :span="18">
                                        <el-tag type="warning" v-for="item3 in item2.children" :key="item3.id" closable @close="removeRightById(scope.row,item3.id)">
                                            {{item3.authName}}
                                        </el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                    </template>
                </el-table-column>
                <!-- 索引列 -->
                <el-table-column type="index"></el-table-column>
                <el-table-column label="角色名称" prop="roleName"></el-table-column>
                <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
                <el-table-column label="操作" width="300px">
                    <template slot-scope="scope">
                        <el-button type="primary" icon="el-icon-edit" size="mini" @click="showeditDialog(scope.row.id)">编辑</el-button>
                        <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeRoleById(scope.row.id)">删除</el-button>
                        <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRightDialog(scope.row)">分配权限</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <!-- 添加角色的弹窗 -->
        <el-dialog
            title="添加角色"
            :visible.sync="addRolesDialogVisiable"
            width="50%"
            @close="addDialogClosed">
            <el-form :model="addRolesForm" ref="addFormRef" label-width="80px" :rules="addRoleRules">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="addRolesForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="addRolesForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
            <el-button @click="addRolesDialogVisiable = false">取 消</el-button>
            <el-button type="primary" @click="addRole">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 编辑角色信息的弹窗 -->
        <el-dialog
            title="修改角色"
            :visible.sync="editDialogVisiable"
            width="50%"
            @close="editRoleClosed"
            >
            <el-form :model="editRolesForm" ref="editFormRef" label-width="80px" :rules="editRoleRules">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="editRolesForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="editRolesForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
            <el-button @click="editDialogVisiable = false">取 消</el-button>
            <el-button type="primary" @click="editRole">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 分配权限的对话框 -->
        <el-dialog
            title="分配权限" :visible.sync="setRightDialogVisible" width="50%"
            @close = "setRightDialogClosed"
            >
            <!-- :date 绑定数据源  :props绑定属性对象 -->
            <el-tree :data="rightsList" :props="treeProps" show-checkbox node-key="id"
            default-expand-all
            :default-checked-keys="defKeys"
            ref = "treeRef"
            ></el-tree>

            <span slot="footer" class="dialog-footer">
                <el-button @click="setRightDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="allotRights">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
export default{
    data(){
        return{
            roleList:[],
            //添加角色弹窗
            addRolesDialogVisiable: false,
            addRolesForm:{
                roleName:'',
                roleDesc:''
            },
            addRoleRules:{
                roleName :[
                    {
                        required: true,
                        message: '请输入角色名',
                        trigger: 'blur'
                    }
                ],
                roleDesc :[
                    {
                        required: true,
                        message: '请输入描述',
                        trigger: 'blur'
                    }
                ]
            },
            editRolesForm: '',
            editRoleRules:{
                roleName :[
                    {
                        required: true,
                        message: '请输入角色名',
                        trigger: 'blur'
                    }
                ],
                roleDesc :[
                    {
                        required: true,
                        message: '请输入描述',
                        trigger: 'blur'
                    }
                ]
            },
            editDialogVisiable: false,
            setRightDialogVisible: false,
            rightsList:[], //所有权限的内容
            //树形控件的绑定属性对象
            treeProps:{
                label: 'authName', //看到的名字
                children: 'children' //父子节点通过哪个属性进行嵌套
            },
            defKeys: [],
            //当前即将分配权限的角色ID
            roleId: ''
        }
    },
    created(){
        this.getRolesList()
    },
    methods: {
        async getRolesList(){
            const {data: res } = await this.$http.get('roles')
            if(res.meta.status !== 200){
                return this.$message.error('获取角色列表失败！')
            }
            this.roleList = res.data
            console.log(this.roleList)
        },
        addDialogClosed(){
            this.$refs.addFormRef.resetFields()
        },
        addRole(){
            //先进行与验证
            this.$refs.addFormRef.validate(async valid =>{
                if(!valid) return
                const {data: res} = await this.$http.post('roles',this.addRolesForm)
                if(res.meta.status !== 201){
                    return this.$message.error('添加角色失败！')
                }
                this.$message.success('添加角色成功！')
                this.addRolesDialogVisiable = false
                this.getRolesList()
            })
        },

        //编辑角色
        async showeditDialog(id){
            const {data: res} = await this.$http.get('roles/'+id)
            if(res.meta.status !== 200){
                return this.$message.error('查询角色信息失败！')
            }
            this.editRolesForm = res.data
            this.editDialogVisiable = true
        },
        editRole(){
            this.$refs.editFormRef.validate(async valid =>{
                if(!valid) return

                const {data: res} = await this.$http.put('roles/'+this.editRolesForm.id,{
                    roleName: this.editRolesForm.roleName,
                    roleDesc: this.editRolesForm.roleDesc
                })
                if(res.meta.status !== 400){
                    return this.$message.error('更新角色信息失败！')
                }
                this.editDialogVisiable = false
                this.getRolesList()
                return this.$message.success('更新角色信息成功！')
            })
        },
        //关闭编辑弹窗并重置
        editRoleClosed(){
            this.$refs.editFormRef.resetFields()
        },
        async removeRoleById(id){
            const confirmResult = await this.$confirm('此操作将永久删除该角色, 是否继续?','提示',{
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(error => error)

            if(confirmResult !== 'confirm'){
                return this.$message.info('已取消删除')
            }
            const {data: res} = await this.$http.delete('roles/'+id)
            if(res.meta.status !== 200){
                return this.$message.error('删除角色失败！')
            }
            this.$message.success('删除角色成功！')
            this.getRolesList()
        },
        //删除角色的三级权限
        async removeRightById(role,rightId){
            const confirmResult = await this.$confirm('此操作将永久删除该权限, 是否继续?','提示',{
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(error =>error)
            if(confirmResult!=='confirm'){
                return this.$message.info('已取消删除');
            }
            const {data: res} = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
            if(res.meta.status!==200){
                return this.$message.error('删除权限失败！')
            }
            // this.getRolesList(); 会重新渲染整个页面，打开的下拉框会合上
            role.children = res.data

        },
        async setRightDialog(role){
            this.roleId = role.id

            const {data: res} = await this.$http.get('rights/tree')
            if(res.meta.status!==200){
                return this.$message.error('获取权限数据失败')
            }
            this.rightsList = res.data
            //获取三级节点的id
            this.getleafKeys(role,this.defKeys)
            this.setRightDialogVisible = true
        },
        //通过递归将角色下的三级权限的id保存到defKeys数组中
        getleafKeys(node,arr){
            if(!node.children){
                return arr.push(node.id)
            }
            //递归获取节点传参
            node.children.forEach(item =>
            this.getleafKeys(item,arr))
        },
        //关闭分配权限对话框后重置三级权限的id数组
        setRightDialogClosed(){
            this.defKeys = []
        },
        //点击为角色分配权限
        async allotRights(){
            const keys = [
                ...this.$refs.treeRef.getCheckedKeys(),
                ...this.$refs.treeRef.getHalfCheckedKeys()
            ]
            const idStr = keys.join(',')

            const {data: res} = await this.$http.post(`roles/${this.roleId}/rights`,{rids : idStr})
            if(res.meta.status!==200){
                return this.$message.error('分配权限失败！')
            }
            this.$message.success('分配权限成功！')
            this.getRolesList()
            this.setRightDialogVisible = false
       }
    }
}
</script>

<style scoped>
.el-tag{
    margin: 7px;
}
.bdtop{
    border-top: 1px solid #eee;
}
.bdbottom{
    border-bottom: 1px solid #eee;
}
.vcenter{
    display: flex;
    align-items: center;
}
</style>
